package org.budo.activiti.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.budo.support.lang.util.StringUtil;

/**
 * @author lmw
 */
public class PNGTranscoderUtil {
    public static byte[] pngTranscode(String svgXml) {
        InputStream inputStream = new ByteArrayInputStream(StringUtil.getUtf8Bytes(svgXml));
        TranscoderInput transcoderInput = new TranscoderInput(inputStream);

        // Setup output
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        TranscoderOutput transcoderOutput = new TranscoderOutput(outputStream);

        // Do the transformation
        PNGTranscoder transcoder = new PNGTranscoder();
        transcode(transcoderInput, transcoderOutput, transcoder);

        byte[] result = outputStream.toByteArray();
        return result;
    }

    private static void transcode(TranscoderInput transcoderInput, TranscoderOutput transcoderOutput, PNGTranscoder transcoder) {
        try {
            transcoder.transcode(transcoderInput, transcoderOutput);
        } catch (TranscoderException e) {
            throw new RuntimeException(e);
        }
    }
}